import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';

/// 网速测试页面
class SpeedTestScreen extends StatefulWidget {
  const SpeedTestScreen({super.key});

  @override
  State<SpeedTestScreen> createState() => _SpeedTestScreenState();
}

class _SpeedTestScreenState extends State<SpeedTestScreen>
    with SingleTickerProviderStateMixin {
  bool _isTesting = false;
  double _downloadSpeed = 0.0;
  double _uploadSpeed = 0.0;
  int _ping = 0;
  String _status = '准备测试';
  
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    )..repeat(reverse: true);
    
    _scaleAnimation = Tween<double>(begin: 0.95, end: 1.05).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  Future<void> _startTest() async {
    if (_isTesting) return;

    setState(() {
      _isTesting = true;
      _downloadSpeed = 0;
      _uploadSpeed = 0;
      _ping = 0;
      _status = '正在测试Ping...';
    });

    // 模拟Ping测试
    await _testPing();

    // 模拟下载速度测试
    setState(() => _status = '正在测试下载速度...');
    await _testDownload();

    // 模拟上传速度测试
    setState(() => _status = '正在测试上传速度...');
    await _testUpload();

    setState(() {
      _isTesting = false;
      _status = '测试完成';
    });
  }

  Future<void> _testPing() async {
    final random = Random();
    for (int i = 0; i < 10; i++) {
      await Future.delayed(const Duration(milliseconds: 100));
      setState(() {
        _ping = 10 + random.nextInt(90); // 10-100ms
      });
    }
  }

  Future<void> _testDownload() async {
    final random = Random();
    for (int i = 0; i < 20; i++) {
      await Future.delayed(const Duration(milliseconds: 100));
      setState(() {
        _downloadSpeed = (random.nextDouble() * 100).clamp(0, 100);
      });
    }
  }

  Future<void> _testUpload() async {
    final random = Random();
    for (int i = 0; i < 20; i++) {
      await Future.delayed(const Duration(milliseconds: 100));
      setState(() {
        _uploadSpeed = (random.nextDouble() * 50).clamp(0, 50);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final bool hasResults = _downloadSpeed > 0 || _uploadSpeed > 0 || _ping > 0;
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('网速测试'),
        elevation: 0,
        actions: [
          if (hasResults && !_isTesting)
            TextButton.icon(
              onPressed: _startTest,
              icon: const Icon(Icons.refresh, color: Colors.white),
              label: const Text('重新测试', style: TextStyle(color: Colors.white)),
            ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Theme.of(context).colorScheme.primary.withOpacity(0.1),
              Colors.white,
            ],
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(24),
            child: Column(
              children: [
                const SizedBox(height: 20),
                
                // 主测试按钮或结果仪表盘
                if (!hasResults || _isTesting) ...[
                  // 主测试按钮
                  GestureDetector(
                    onTap: _isTesting ? null : _startTest,
                    child: AnimatedBuilder(
                      animation: _scaleAnimation,
                      builder: (context, child) {
                        return Transform.scale(
                          scale: _isTesting ? _scaleAnimation.value : 1.0,
                          child: Container(
                            width: 200,
                            height: 200,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              gradient: LinearGradient(
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                                colors: _isTesting
                                    ? [
                                        Theme.of(context).colorScheme.primary,
                                        Theme.of(context).colorScheme.primary.withOpacity(0.7),
                                      ]
                                    : [
                                        Colors.blue,
                                        Colors.blue.shade700,
                                      ],
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                                  blurRadius: 20,
                                  spreadRadius: 5,
                                ),
                              ],
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  _isTesting ? Icons.speed : Icons.play_arrow,
                                  size: 60,
                                  color: Colors.white,
                                ),
                                const SizedBox(height: 12),
                                Text(
                                  _isTesting ? '测试中...' : '开始测试',
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 状态文字
                  Text(
                    _status,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey.shade700,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ] else ...[
                  // 测试完成 - 显示仪表盘样式结果
                  _buildSpeedometer(context),
                  
                  const SizedBox(height: 24),
                  
                  // 测试完成徽章
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Colors.green,
                          Colors.green.shade700,
                        ],
                      ),
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.green.withOpacity(0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(
                          Icons.check_circle,
                          color: Colors.white,
                          size: 20,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          _status,
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
                
                const SizedBox(height: 40),
                
                // 详细结果卡片
                _buildResultCard(
                  context,
                  icon: Icons.network_ping,
                  title: 'Ping',
                  value: _ping > 0 ? '$_ping' : '--',
                  unit: 'ms',
                  color: _getPingColor(_ping),
                ),
                
                const SizedBox(height: 16),
                
                _buildResultCard(
                  context,
                  icon: Icons.download,
                  title: '下载速度',
                  value: _downloadSpeed > 0 ? _downloadSpeed.toStringAsFixed(2) : '--',
                  unit: 'Mbps',
                  color: Colors.green,
                  showProgress: _isTesting && _status.contains('下载'),
                  progress: _downloadSpeed / 100,
                ),
                
                const SizedBox(height: 16),
                
                _buildResultCard(
                  context,
                  icon: Icons.upload,
                  title: '上传速度',
                  value: _uploadSpeed > 0 ? _uploadSpeed.toStringAsFixed(2) : '--',
                  unit: 'Mbps',
                  color: Colors.orange,
                  showProgress: _isTesting && _status.contains('上传'),
                  progress: _uploadSpeed / 50,
                ),
                
                const SizedBox(height: 32),
                
                // 提示信息
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Theme.of(context).brightness == Brightness.dark
                        ? Colors.blue.shade900.withOpacity(0.2)
                        : Colors.blue.shade50,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: Theme.of(context).brightness == Brightness.dark
                          ? Colors.blue.shade700.withOpacity(0.5)
                          : Colors.blue.shade200,
                      width: 1,
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(
                        Icons.info_outline,
                        color: Colors.blue.shade700,
                        size: 24,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Text(
                          '提示：测试结果仅供参考，实际速度可能受网络状况影响',
                          style: TextStyle(
                            fontSize: 13,
                            color: Colors.blue.shade700,
                            height: 1.4,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建仪表盘样式的速度展示
  Widget _buildSpeedometer(BuildContext context) {
    return Container(
      width: 280,
      height: 280,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: Theme.of(context).brightness == Brightness.dark
              ? [
                  Colors.blue.shade900.withOpacity(0.3),
                  Colors.grey.shade900,
                ]
              : [
                  Colors.blue.shade50,
                  Colors.white,
                ],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.withOpacity(0.2),
            blurRadius: 30,
            spreadRadius: 5,
          ),
        ],
      ),
      child: Stack(
        children: [
          // 外圈装饰
          Positioned.fill(
            child: CustomPaint(
              painter: SpeedometerPainter(
                downloadSpeed: _downloadSpeed,
                uploadSpeed: _uploadSpeed,
              ),
            ),
          ),
          
          // 中心内容
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 速度图标
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    gradient: LinearGradient(
                      colors: [
                        Theme.of(context).colorScheme.primary,
                        Theme.of(context).colorScheme.primary.withOpacity(0.7),
                      ],
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                        blurRadius: 12,
                        spreadRadius: 2,
                      ),
                    ],
                  ),
                  child: const Icon(
                    Icons.speed,
                    color: Colors.white,
                    size: 32,
                  ),
                ),
                
                const SizedBox(height: 16),
                
                // 下载速度（主显示）
                Text(
                  _downloadSpeed.toStringAsFixed(1),
                  style: TextStyle(
                    fontSize: 48,
                    fontWeight: FontWeight.bold,
                    color: Colors.green.shade700,
                    height: 1,
                  ),
                ),
                
                const SizedBox(height: 4),
                
                Text(
                  'Mbps',
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.grey.shade600,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                
                const SizedBox(height: 8),
                
                // 下载/上传小标签
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _buildSpeedLabel(
                      icon: Icons.download,
                      label: '下载',
                      color: Colors.green,
                    ),
                    const SizedBox(width: 20),
                    _buildSpeedLabel(
                      icon: Icons.upload,
                      label: '上传 ${_uploadSpeed.toStringAsFixed(1)} Mbps',
                      color: Colors.orange,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSpeedLabel({
    required IconData icon,
    required String label,
    required Color color,
  }) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 16, color: color),
        const SizedBox(width: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: color,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  Widget _buildResultCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String value,
    required String unit,
    required Color color,
    bool showProgress = false,
    double progress = 0,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16),
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              color.withOpacity(0.1),
              Colors.white,
            ],
          ),
        ),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: color.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(
                    icon,
                    color: color,
                    size: 28,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey.shade600,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.baseline,
                        textBaseline: TextBaseline.alphabetic,
                        children: [
                          Text(
                            value,
                            style: TextStyle(
                              fontSize: 32,
                              fontWeight: FontWeight.bold,
                              color: color,
                            ),
                          ),
                          const SizedBox(width: 8),
                          Text(
                            unit,
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.grey.shade600,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
            if (showProgress) ...[
              const SizedBox(height: 12),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: LinearProgressIndicator(
                  value: progress,
                  backgroundColor: Colors.grey.shade200,
                  valueColor: AlwaysStoppedAnimation(color),
                  minHeight: 8,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Color _getPingColor(int ping) {
    if (ping == 0) return Colors.grey;
    if (ping < 50) return Colors.green;
    if (ping < 100) return Colors.orange;
    return Colors.red;
  }
}

/// 仪表盘绘制器
class SpeedometerPainter extends CustomPainter {
  final double downloadSpeed;
  final double uploadSpeed;
  
  SpeedometerPainter({
    required this.downloadSpeed,
    required this.uploadSpeed,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2 - 20;
    
    // 背景圆环
    final bgPaint = Paint()
      ..color = Colors.grey.shade200
      ..style = PaintingStyle.stroke
      ..strokeWidth = 12
      ..strokeCap = StrokeCap.round;
    
    canvas.drawCircle(center, radius, bgPaint);
    
    // 下载速度圆弧（绿色）
    final downloadPaint = Paint()
      ..shader = LinearGradient(
        colors: [
          Colors.green.shade400,
          Colors.green.shade700,
        ],
      ).createShader(Rect.fromCircle(center: center, radius: radius))
      ..style = PaintingStyle.stroke
      ..strokeWidth = 12
      ..strokeCap = StrokeCap.round;
    
    final downloadSweep = (downloadSpeed / 100) * 2 * pi * 0.75; // 最多显示75%的圆
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -pi / 2, // 从顶部开始
      downloadSweep,
      false,
      downloadPaint,
    );
    
    // 上传速度圆弧（橙色，在下载速度之后）
    final uploadPaint = Paint()
      ..shader = LinearGradient(
        colors: [
          Colors.orange.shade400,
          Colors.orange.shade700,
        ],
      ).createShader(Rect.fromCircle(center: center, radius: radius))
      ..style = PaintingStyle.stroke
      ..strokeWidth = 8
      ..strokeCap = StrokeCap.round;
    
    final uploadSweep = (uploadSpeed / 50) * 2 * pi * 0.25; // 最多显示25%的圆
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius - 16),
      -pi / 2 + downloadSweep + 0.1,
      uploadSweep,
      false,
      uploadPaint,
    );
    
    // 装饰性刻度线
    final tickPaint = Paint()
      ..color = Colors.grey.shade300
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2;
    
    for (int i = 0; i < 12; i++) {
      final angle = (i / 12) * 2 * pi - pi / 2;
      final startRadius = radius + 8;
      final endRadius = radius + 16;
      
      final start = Offset(
        center.dx + startRadius * cos(angle),
        center.dy + startRadius * sin(angle),
      );
      final end = Offset(
        center.dx + endRadius * cos(angle),
        center.dy + endRadius * sin(angle),
      );
      
      canvas.drawLine(start, end, tickPaint);
    }
  }

  @override
  bool shouldRepaint(SpeedometerPainter oldDelegate) {
    return oldDelegate.downloadSpeed != downloadSpeed ||
           oldDelegate.uploadSpeed != uploadSpeed;
  }
}
